package cn.itcast.cloud.storage;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CompleteMultipartUploadResult;
import com.aliyun.oss.model.UploadFileRequest;
import com.aliyun.oss.model.UploadFileResult;
import org.junit.Test;

/**
 * 断点续传上传
 */
public class UploadSample {
    private static String endpoint = "http://oss-cn-zhangjiakou.aliyuncs.com";
    private static String accessKeyId = "LTAIXeZktAHXvAgc";
    private static String accessKeySecret = "iHpKZJ5KiB7imcohA7VgjDzLY2O87w";
    private static String bucketName = "jiaze";
    private static String key = "attaches";
    private static String uploadFile = "C:\\Users\\zhangtian\\Desktop\\使用SpringCloud和Docker实战微服务.pdf";

    @Test
    public void testUpload(){
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        try {
            UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, key) ;
            // The local file to upload---it must exist.
            uploadFileRequest.setUploadFile(uploadFile);
            // Sets the concurrent upload task number to 5.
            uploadFileRequest.setTaskNum(5);
            // Sets the part size to 1MB.
            uploadFileRequest.setPartSize(1024 * 1024 * 5);
            // Enables the checkpoint file. By default it's off.  开启断点续传开关
            uploadFileRequest.setEnableCheckpoint(true);

            UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest) ;
            CompleteMultipartUploadResult multipartUploadResult = uploadResult.getMultipartUploadResult();
            System.out.println(multipartUploadResult.getKey());
            System.out.println(multipartUploadResult.getLocation());
            System.out.println(multipartUploadResult.getETag());
        }catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message: " + oe.getErrorCode());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ce.getMessage());
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
    }
}
